package wymiana.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import wymiana.dao.MailDao;
import wymiana.domain.Mail;
import wymiana.domain.User;


@Service("mailService")
@Transactional
public class MailService {

	@Autowired
	private MailDao mailDao;

	public List<Mail> getAllMails() {
		return mailDao.getAll();
	}

	public Mail getMailById(Long id) {
		return mailDao.getById(id);
	}

	public List<Mail> getMailsBySender(User sender) {
		List<Mail> list1 = mailDao.getBySender(sender);
		List<Mail> list2 = new ArrayList<Mail>();
		int i = list1.size() - 1;
		while (i > -1) {
			list2.add(list1.get(i));
			i--;
		}

		return list2;
	}

	public List<Mail> getMailsByRecipient(User recipient) {
		List<Mail> list1 = mailDao.getByRecipient(recipient);
		List<Mail> list2 = new ArrayList<Mail>();
		int i = list1.size() - 1;
		while (i > -1) {
			list2.add(list1.get(i));
			i--;
		}

		return list2;
	}

	public Mail getMailByUserAndId(User user, Long id) {
		List<Mail> mails = mailDao.getMailByUserAndId(user, id);
		if (mails == null)
			return null;
		else if (mails.isEmpty())
			return null;

		return mails.get(0);
	}

	public boolean sendMail(Mail mail) {
		mailDao.save(mail);
		return true;
	}

	public void deleteById(Long id) {
		mailDao.delete(id);
	}

	public void updateMail(Mail mail) {
		mailDao.saveOrUpdate(mail);
	}

	public List<Mail> getMailsByUserTrash(User user) {
		List<Mail> list1 = mailDao.getMailsByTrash(user);
		List<Mail> list2 = new ArrayList<Mail>();
		int i = list1.size() - 1;
		while (i > -1) {
			list2.add(list1.get(i));
			i--;
		}
		return list2;
	}

	@SuppressWarnings("unchecked")
	public int getNewMailsCount(User user) {
		List list = mailDao.getNewMailsCount(user);
		String count = "0";
		if (list.size() > 0) {
			System.out.println("" + list.get(0));
			count = "" + list.get(0);
		}
		return Integer.parseInt(count);
	}

}
